package com.dolawing.phonecallapp.listenphonecall;

import android.app.ActivityManager;
import android.app.KeyguardManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import java.util.List;

/**
 * 电话服务 闹钟广播，接受来自 MainActivity中发出的 定时闹钟广播
 */
public class PhoneServiceRestartReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent callListener = new Intent(context, CallListenerService.class);
        KeyguardManager mKeyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
        boolean flag = mKeyguardManager.inKeyguardRestrictedInputMode();
        boolean isAlive = isServiceWorked(context,"com.dolawing.phonecallapp.listenphonecall.PhoneServiceRestartReceiver");
        Log.i("锁屏状态",String.valueOf(flag));
        Log.i("Service存活状态",String.valueOf(isAlive));
        if (flag==true){  //锁屏时
            context.stopService(callListener); //关闭服务
            context.startService(callListener);
        }else if(isAlive==false){ //未锁屏时,但服务不存在
            context.stopService(callListener); //关闭服务
            context.startService(callListener);
        }else{
            context.startService(callListener);
        }
//        App.getAlarmInstance().registAlarm(context);  //闹钟执行后，需重新注册 闹钟
    }

    /**
     * 用来检测Service是否还活着
     * 如： boolean isAlive = isServiceWorked(context,"com.dolawing.phonecallapp.listenphonecall.PhoneServiceRestartReceiver");
     * @param context
     * @param serviceName
     * @return
     */
    public static boolean isServiceWorked(Context context, String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(100);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getClassName().toString();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }

}
